import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface ThemeContextType {
  dark: boolean;
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const useTheme = (): ThemeContextType => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

interface ThemeProviderProps {
  children: ReactNode;
}

export function ThemeProvider({ children }: ThemeProviderProps) {
  // 初始化时从localStorage读取
  const [dark, setDark] = useState<boolean>(() => {
    const stored = localStorage.getItem('darkTheme');
    return stored === 'true';
  });

  // 切换时写入localStorage
  const toggleTheme = (): void => {
    setDark(d => {
      localStorage.setItem('darkTheme', (!d).toString());
      return !d;
    });
  };

  // 兼容外部直接修改localStorage的情况
  useEffect(() => {
    localStorage.setItem('darkTheme', dark.toString());
  }, [dark]);

  return (
    <ThemeContext.Provider value={{ dark, toggleTheme }}>
      <div className={dark ? 'dark-theme' : ''}>
        {children}
      </div>
    </ThemeContext.Provider>
  );
} 